<?php
namespace Home\Controller;

use Think\Controller;

class LoginController extends Controller
{
    public function index()
    {
        $this->info();
        $this->display();
    }
    public function reg()
    {
        $this->info();
    	$this->display();
    }
    public function ajaxLogin()
    {
    	if(!IS_AJAX){
            $this->error('提交方式错误!');
        }else{
        	$name=remove_xss(trim($_POST['name']));
            $pwd =remove_xss(trim($_POST['pass']));
            $user=M('user')->where(array('username'=>$name,'password'=>md5($pwd)))->find();
            if(!empty($user)){
            	$_SESSION['user']['id']=$user['id'];
                $uid=(int)$_SESSION['user']['id'];
                $usertime=(int)$user['lasttime'];//获取最后登录时间
                $nowtime=time();
                $re=$nowtime-$lasttime;
                if ($re>86400) {
                    //重置次数
                    //查询次数
                    $info=M('info')->where("id=1")->find();
                    $vipcount=$info['vipcount'];
                    $usercount=$info['usercount'];
                    $data['vipcount']=$vipcount;
                    $data['usercount']=$usercount;
                    $re=M('user')->where("id=$uid")->save($data);
                }
            	$this->success('登录成功',U('user/index'));
            }else{
            	$this->error('用户不存在，或者密码错误');
            }
        }
    }
    public function ajaxReg()
    {
    	if(!IS_AJAX){
            $this->error('提交方式错误!');
        }else{
            $info=M('info')->where("id=1")->find();
            $vcount = $info['vipcount'];
            if ($vcount>0) {
                $data['vipcount'] = $vcount;
            }
            $ucount = $info['usercount'];
            if ($ucount>0) {
                $data['usercount'] = $ucount;
            }
	    	$data['username']=remove_xss(trim($_POST['name']));
			$data['password'] =md5(remove_xss(trim($_POST['pass'])));
	        $data['qq'] =remove_xss(trim($_POST['qq']));
	        $username=remove_xss(trim($_POST['name']));
	        $qq=remove_xss(trim($_POST['qq']));
            //最后登录时间
            $data['lasttime']=time();
	        $re=M('user')->where("username='$username'")->select();
            
	        $re1=M('user')->where("qq='$qq'")->select();
	        if (!empty($re)) {
	        	$this->error('该用户名已存在！请更换！');
	        }
            if (!empty($re1)) {
                $this->error('该QQ已存在！请更换！');
            }
	        $user=M('user')->add($data);
	        if (!empty($user)) {
	        	$_SESSION['user']['id']=$user;
            	$this->success('注册成功~正在登陆',U('user/index'));
	        }else{
	        	$this->error('注册失败');
	        }
	    }
    }
    function info(){
      $info=M('info')->where("id=1")->find();
      $this->assign('info',$info);
    }
    
}
